<?php

namespace app\index\controller;

use app\common\controller\Log;
use app\common\model\Member;
use think\Request;


class MemberGroupsChat extends Home
{
    private static $model;

    protected $beforeActionList = [
        'check_load'
    ];

    public function __construct(Request $request = null)
    {
        parent::__construct($request);

        self::$model = new \app\common\model\MemberGroupsChat();
    }

    /**
     * 群聊记录
     */
    public function lists()
    {
        $uid = $this->uid;
        $page = input('page');
        $start = ($page - 1) * self::$totalList;

        $group_id = input('group_id');

        $lists = self::$model->where('status', 1)
            ->where('group_id', $group_id)
            ->order('id desc')
            ->limit($start, self::$totalList)
            ->select();

        $totalCount = self::$model->where('status', 1)
            ->where('group_id', $group_id)
            ->count();

        if ($totalCount > 0) {
            foreach ($lists as $k => $v) {
                $lists[$k] = self::getAllData($v, $uid);
            }
        }

        $this->apiSuccess('群聊记录', ['list' => $lists, 'totalCount' => $totalCount]);
    }

    /**
     * Notes:记录聊天内容
     * User: Administrator
     * Date: 2023/9/13
     * Time: 11:38
     * @param $dataStr
     */
    public static function add($dataStr)
    {
        $dataObj = json_decode($dataStr);

        $uid = $dataObj->fromUserId;
        $data = [
            'group_id' => $dataObj->chatGroupId,
            'uid' => $uid,
            'msg_type' => 1,
            'content_type' => $dataObj->contentType,
            'content' => $dataObj->content,
        ];

        $res = \app\common\model\MemberGroupsChat::create($data);
        $ndata = self::getAllData($res, $uid);
        Log::insertLog($ndata);
        return $ndata;
    }

    /**
     * 数据补全
     * @param $obj
     * @param $uid
     */
    private static function getAllData($obj, $uid)
    {
        $obj->msgType = $obj->msg_type;
        $obj->contentType = $obj->content_type;
//        $obj->meFlag = false;
        $member = Member::find($obj->uid);
        $obj->userName = $member->usernumber;
        $obj->userAvatar = $member->icon > 0 ? get_cover($obj->icon, 'path') : '';

        return $obj;
    }
}